import Vue from 'vue'
import Vuex from 'vuex'
import network from "../network/index"
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    GoodsList: [], //渲染
    AddLocal: JSON.parse(localStorage.getItem('GoodsList')) || [],   //加入购物车列表
    Allcheckbox: JSON.parse(localStorage.getItem('checkbox')) || false,
    allmoney:0
  },
  mutations: {
    GOODSLIST(state, item) {
      state.GoodsList = item
    },
    // 加入购物车
    ADDLOCAL(state, item) {
      var isShow = false
      state.AddLocal.map((ele) => {
        if (ele.subcid == item.subcid) {
          isShow = true
          ele.count++
        }
      })
      if (!isShow) {
        item.count = 1;
        item.checked = false;
        item.price=100
        state.AddLocal.push(item)
      }
      localStorage.setItem('GoodsList',JSON.stringify(state.AddLocal))
    },
    // 复选框
    CHECKEDCLICK(state, item) {
      item.checked = !item.checked
      state.AddLocal.forEach(element => {
        if (element.subcid == item.subcid) {
          element.checked = item.checked
        }
      });
      // 点击的复选框都为true 让 全选动态绑定的也选中 一个不是true 就不选中
      let allLIST = state.AddLocal.every((ele) => {
        return ele.checked == true
      })
      state.Allcheckbox = allLIST

      // 计算价格
      state.allmoney = 0
      state.AddLocal.forEach((ele)=>{
       if(ele.checked == true){
        state.allmoney+= ele.count*ele.price
       }
      })
      // console.log(state.allmoney);
      
    },
    // 全选
    ALL(state, check) {
      state.Allcheckbox = check
      if (state.Allcheckbox) {
        state.AddLocal.map((ele) => {
          ele.checked = check
        })
      }else{
        state.AddLocal.map((ele) => {
          ele.checked = check
        })
      }
       // 计算价格
       state.allmoney = 0
       state.AddLocal.forEach((ele)=>{
        if(ele.checked == true){
         state.allmoney+= ele.count*ele.price
        }
       })
       console.log(state.allmoney);
    }
  },
  actions: {
    // 渲染
    GOODSLIST(context) {
      network.getStoreDoods({

      }).then((res) => {
        console.log(res.data.data.data);
        context.commit('GOODSLIST', res.data.data.data)
      })
    },
    // 加入购物车
    ADDLOCAL(context, item) {
      context.commit('ADDLOCAL', item)
    },
    // 复选框
    CHECKEDCLICK(context, item) {
      context.commit('CHECKEDCLICK', item)
    },
    // 全选
    ALL(context, check) {
      context.commit('ALL', check)
    }
  },
  modules: {
  }
})
